//
//  UserAccount.swift
//  SinaWeiBo20
//
//  Created by tarena on 16/3/21.
//  Copyright © 2016年 tarena. All rights reserved.
//

import UIKit

class UserAccount: NSObject {
    
    
//    //单例模式
//    static let sharedInstance = UserAccount()
//    private override init() { }
//    //用户是否登录
//    var userLogin : Bool = false
    
    //用于调用access_token，接口获取授权后的access token。
    var access_token : String?
    
    //access_token的生命周期，单位是秒数。
    var expires_in : NSTimeInterval = 0{
        didSet{
            expires_date = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    var expires_date: NSDate?
    
    //当前授权用户的UID
    var uid :String?
    
    //用户头像地址（大图），180×180像素
    var avatar_large :String?
    
    //友好显示名称
    var name :String?
    
    init(dict : [String : AnyObject]){
        super.init()
        setValuesForKeysWithDictionary(dict)
    }

    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    override var description: String {
        
        let keys = ["access_token","expires_in","uid","avatar_large","name","expires_date"]
        return "\(dictionaryWithValuesForKeys(keys))"
        
        
    }
    
    
    
    
    //存取的地址
    static let accountPath = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.plist")
    
    
    //归档 存档
    func saveAccount() {
        NSKeyedArchiver.archiveRootObject(self, toFile: UserAccount.accountPath)
    }
    
    //从磁盘中获取缓存 的自定义对象
    class func shareUserAccount() ->UserAccount? {
        
        if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(UserAccount.accountPath) as? UserAccount {
            if account.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
                return account
            }
        }
        return nil
    }
    
    
    func encodeWithCoder(aCoder: NSCoder) {
        
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(expires_date, forKey: "expires_date")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        aCoder.encodeObject(name, forKey: "name")
        
    }
    
    
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token")as? String
        uid = aDecoder.decodeObjectForKey("uid") as? String
        expires_date = aDecoder.decodeObjectForKey("expires_date") as? NSDate
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
        name = aDecoder.decodeObjectForKey("name") as? String
        
    }
    
    
    
}
